package com.bjy.qa.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjy.qa.dao.user.UserCompanyProjectDao;
import com.bjy.qa.entity.user.UserCompanyProject;
import com.bjy.qa.exception.MyException;
import com.bjy.qa.service.user.IUserCompanyProjectService;
import com.bjy.qa.util.security.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserCompanyProjectService extends ServiceImpl<UserCompanyProjectDao, UserCompanyProject> implements IUserCompanyProjectService {
    @Resource
    UserCompanyProjectDao userCompanyProjectDao;

    @Override
    public boolean hasUserProjectPermissions(Long companyId, Long projectId) {
        if (projectId == null) {
            throw new MyException("projectId（项目ID ）不能为空，请重试！");
        }

        if (SecurityUtils.getCurrentUserProjectId() == projectId) { // 如果要校验的 projectId 跟 security 相同，则返回 true
            return true;
        } else { // 在数据库中查询是否有项目权限
            QueryWrapper<UserCompanyProject> queryUserCompanyProjectWrapper = new QueryWrapper<>();
            queryUserCompanyProjectWrapper.eq("user_id", SecurityUtils.getCurrentUserId());
            if (companyId != null) {
                queryUserCompanyProjectWrapper.eq("company_id", companyId);
            }
            queryUserCompanyProjectWrapper.eq("project_id", projectId);
            if (userCompanyProjectDao.selectCount(queryUserCompanyProjectWrapper) > 0) {
                return true;
            } else {
                return false;
            }
        }
    }
}
